package com.example.listviewtest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class FruitAdapter extends ArrayAdapter<Fruit> {

    private int resourceId;
    private Context context;

    public FruitAdapter(Context context, int itemLayoutId, List<Fruit> data){
        super(context,itemLayoutId,data);
        resourceId = itemLayoutId;
        this.context = context;
    }


    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view;
        ViewHolder viewHolder;
        if(convertView == null){
            view = LayoutInflater.from(context).inflate(resourceId,parent,false);
            viewHolder = new ViewHolder();
            viewHolder.setImageView((ImageView) view.findViewById(R.id.fruit_image));
            viewHolder.setTextView((TextView) view.findViewById(R.id.fruit_name));
            view.setTag(viewHolder);
        }else {
            view = convertView;
            viewHolder = (ViewHolder)view.getTag();
        }

        ImageView imageView = viewHolder.getImageView();
        TextView textView = viewHolder.getTextView();
        Fruit fruit = getItem(position);
        imageView.setImageResource(fruit.getImageId());
        textView.setText(fruit.getName());

        return view;
    }
}
